<template>
  <div>
    <AModal
      v-bind="$attrs"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="formRef" :model="form" auto-label-width>
        <AFormItem
          field="feeCategory"
          label="费用分类"
          :rules="[{ required: true, message: '请输入费用分类' }]"
          :validate-trigger="['change', 'input', 'blur']"
          :content-flex="false"
        >
          <AInput v-model="form.feeCategory" placeholder="费用分类" @input="throttled" />
          <div style="font-size: 12px; color: #ff8900">
            当值为货款或者材料款且作用对象存在时，报表才会自动汇总数据
          </div>
        </AFormItem>
        <AFormItem
          field="accountName"
          label="账户名称"
          :rules="[{ required: true, message: '请输入账户名称' }]"
          :validate-trigger="['change', 'input', 'blur']"
        >
          <AInput
            v-model="form.accountName"
            placeholder="账户名称"
            :disabled="!(attrs.title as string).includes('新增')"
          />
        </AFormItem>
        <AFormItem field="tradeDt" label="交易时间">
          <ADatePicker
            v-model="form.tradeDt"
            placeholder="交易时间"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            class="w100"
          ></ADatePicker>
        </AFormItem>
        <AFormItem field="bankAccount" label="账户号">
          <AInput
            v-model="form.bankAccount"
            placeholder="账户号"
            :disabled="!(attrs.title as string).includes('新增')"
          />
        </AFormItem>
        <AFormItem field="feeUsage" label="费用用途">
          <AInput v-model="form.feeUsage" placeholder="费用用途" />
        </AFormItem>
        <AFormItem field="incomeAmt" label="收入">
          <AInputNumber
            v-model="form.incomeAmt"
            model-event="input"
            placeholder="收入"
            hide-button
            :precision="2"
            :step="0.1"
          />
        </AFormItem>
        <AFormItem field="expendAmt" label="支出">
          <AInputNumber
            v-model="form.expendAmt"
            model-event="input"
            placeholder="支出"
            hide-button
            :precision="2"
            :step="0.1"
          />
        </AFormItem>
        <AFormItem field="usedObj" label="作用对象">
          <ASelect
            v-if="['货款', '材料款'].includes(form.feeCategory)"
            v-model="form.usedObj"
            placeholder="作用对象"
            allow-search
          >
            <AOption
              v-for="(item, index) in usedObjOption"
              :key="index"
              :label="item.Name"
              :value="item.Name"
            ></AOption>
          </ASelect>
          <AInput v-else v-model="form.usedObj" placeholder="作用对象" />
        </AFormItem>
        <AFormItem field="remark" label="备注">
          <ATextarea v-model="form.remark" placeholder="备注"></ATextarea>
        </AFormItem>
        <AFormItem field="attachFiles" label="附件">
          <upload v-model:attach-files="attachFiles"></upload>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import {
  AccountReq,
  AccountResItem,
  editAccount,
  getAccountDetail
} from '@renderer/api/accountFlowDetails'
import { deleteNullObject } from '@renderer/utils/data-processing'
import upload from '@renderer/components/upload/index.vue'
import { useMenuState } from '@renderer/store'
import { FileListType } from '@renderer/types/global'
import { batchDelUploadFile } from '@renderer/api/common'
import { differenceBy, isEmpty, throttle } from 'lodash-es'
import {
  CustomerResItem,
  getCustomerAllList,
  getSupplierAllList,
  SupplierResItem
} from '@renderer/api/company'

interface Props {
  [key: string]: any
  checkData?: Partial<AccountResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<AccountReq>({
  bankAccount: '',
  feeCategory: '',
  feeUsage: '',
  incomeAmt: 0,
  expendAmt: 0,
  accountBalance: 0,
  usedObj: '',
  tradeType: 1,
  remark: '',
  fileList: [],
  accountName: ''
})
const attachFiles = ref<FileListType[]>([])
const menuParam = useMenuState()
const usedObjOption = ref<any[]>([])
const companyList = ref<CustomerResItem[]>([])
const supplierList = ref<SupplierResItem[]>([])

// 获取客户
const getCustomerList = () => {
  getCustomerAllList({
    customerName: '',
    taxNo: '',
    contactName: ''
  }).then((res) => {
    companyList.value = res.data.list
  })
}
// 获取供应商
const getSupplierList = () => {
  getSupplierAllList({ supplierName: '' }).then((res) => {
    supplierList.value = res.data.list
  })
}
// 获取详情
const getDetail = () => {
  getAccountDetail({ accountTradeDetailId: props.checkData.accountTradeDetailId! }).then((res) => {
    form.value = res.data
    attachFiles.value = form.value.fileList ? [...form.value.fileList] : []
  })
}
// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate(async (errors: any) => {
        console.log(errors)
        if (!errors) {
          form.value.tradeType = 1
          const delFile = differenceBy(form.value.fileList, attachFiles.value)
          const delFileIds = delFile.map((item) => item.fileId)
          form.value.fileList = attachFiles.value
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.accountTradeDetailId = undefined
          }
          if (!isEmpty(delFileIds)) {
            await batchDelUploadFile({ fileIdList: delFileIds })
          }

          editAccount(deleteNullObject(form.value)).then(() => {
            Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      attachFiles.value = []
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getCustomerList()
      getSupplierList()
      if (attrs.title === '修改') {
        getDetail()
      }
      break
    case 'cancel':
      formRef.value.resetFields()
      menuParam.switchEditStatus(false)
      attachFiles.value = []
      emit('update:visible', false)
      break
    default:
      break
  }
}

// 费用分类
const feeCategoryInput = () => {
  if (form.value.feeCategory === '货款') {
    usedObjOption.value = companyList.value.map((item) => {
      item.Name = item.customerName
      return item
    })
    form.value.usedObj = ''
  } else if (form.value.feeCategory === '材料款') {
    usedObjOption.value = supplierList.value.map((item) => {
      item.Name = item.supplierName
      return item
    })
    form.value.usedObj = ''
  }
}
const throttled = throttle(feeCategoryInput, 1000)
onUnmounted(() => {
  throttled.cancel
})
</script>
<style scoped></style>
